//+------------------------------------------------------------------+
//| 断水流指标 - 线条连续性修复版                                        |
//| 关键修复：正确处理MT5的数组访问和循环方式                             |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 8
#property indicator_plots   3

// 主趋势线 - 使用颜色缓冲区实现动态颜色切换
#property indicator_label1  "Trend Line"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrOrange,clrLimeGreen
#property indicator_style1  STYLE_SOLID
#property indicator_width1  3

// 信号线
#property indicator_label2  "Signal Line"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrMagenta
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1

// 箭头
#property indicator_label3  "Arrows"
#property indicator_type3   DRAW_COLOR_ARROW
#property indicator_color3  clrOrange,clrLimeGreen
#property indicator_style3  STYLE_SOLID
#property indicator_width3  2

// 输入参数
input int             FastEma     = 13;
input int             SlowEma     = 34;
input int             SignalMA    = 8;
input ENUM_MA_METHOD  SignalMAMode = MODE_EMA;
input int             SigMA       = 8;
input ENUM_MA_METHOD  SigMAMode   = MODE_EMA;
input bool            drawArrows  = true;

// 缓冲区 - 关键改变：不使用ArraySetAsSeries
double TrendLineBuffer[];
double TrendColorBuffer[];
double SignalLineBuffer[];
double ArrowBuffer[];
double ArrowColorBuffer[];
double temp1[];
double temp2[];
double state[];

// MA句柄
int fastEmaHandle = INVALID_HANDLE;
int slowEmaHandle = INVALID_HANDLE;
int atrHandle = INVALID_HANDLE;

//+------------------------------------------------------------------+
// 修复版MAOnArray - 使用MT5标准数组访问方式
double MAOnArray_Fixed(const double &array[], int period, ENUM_MA_METHOD ma_method, int shift)
{
   if(period <= 1 || shift < 0) return 0.0;
   
   int arraySize = ArraySize(array);
   if(shift >= arraySize) return 0.0;
   
   // 确保有足够数据
   if(shift + period > arraySize) period = arraySize - shift;
   if(period <= 0) return 0.0;
   
   double sum = 0.0;
   
   switch(ma_method)
   {
      case MODE_SMA:
         for(int i = 0; i < period; i++)
         {
            sum += array[shift + i];
         }
         return sum / period;
         
      case MODE_EMA:
         {
            double alpha = 2.0 / (period + 1.0);
            double ema = array[shift];
            for(int i = 1; i < period; i++)
            {
               if(shift + i < arraySize)
                  ema = alpha * array[shift + i] + (1.0 - alpha) * ema;
            }
            return ema;
         }
         
      default:
         for(int i = 0; i < period; i++)
         {
            sum += array[shift + i];
         }
         return sum / period;
   }
}

//+------------------------------------------------------------------+
int OnInit()
{
   // 设置缓冲区 - 关键：不使用ArraySetAsSeries
   SetIndexBuffer(0, TrendLineBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, TrendColorBuffer, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, SignalLineBuffer, INDICATOR_DATA);
   SetIndexBuffer(3, ArrowBuffer, INDICATOR_DATA);
   SetIndexBuffer(4, ArrowColorBuffer, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(5, temp1, INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, temp2, INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, state, INDICATOR_CALCULATIONS);
   
   // 关键改变：不使用ArraySetAsSeries，使用MT5默认方式
   // ArraySetAsSeries(TrendLineBuffer, true);  // 注释掉这些
   
   // 设置颜色
   PlotIndexSetInteger(0, PLOT_COLOR_INDEXES, 2);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 0, clrOrange);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, 1, clrLimeGreen);
   
   if(drawArrows) {
      PlotIndexSetInteger(2, PLOT_COLOR_INDEXES, 2);
      PlotIndexSetInteger(2, PLOT_LINE_COLOR, 0, clrOrange);
      PlotIndexSetInteger(2, PLOT_LINE_COLOR, 1, clrLimeGreen);
      PlotIndexSetInteger(2, PLOT_ARROW, 159);
   } else {
      PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE);
   }
   
   // 创建MA句柄
   fastEmaHandle = iMA(_Symbol, PERIOD_CURRENT, FastEma, 0, MODE_EMA, PRICE_CLOSE);
   slowEmaHandle = iMA(_Symbol, PERIOD_CURRENT, SlowEma, 0, MODE_EMA, PRICE_CLOSE);
   atrHandle = iATR(_Symbol, PERIOD_CURRENT, 20);
   
   if(fastEmaHandle == INVALID_HANDLE || slowEmaHandle == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
   {
      Print("创建指标句柄失败");
      return INIT_FAILED;
   }
   
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(fastEmaHandle != INVALID_HANDLE) IndicatorRelease(fastEmaHandle);
   if(slowEmaHandle != INVALID_HANDLE) IndicatorRelease(slowEmaHandle);
   if(atrHandle != INVALID_HANDLE) IndicatorRelease(atrHandle);
}

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   if(rates_total < FastEma + SlowEma + SignalMA + SigMA + 10)
      return 0;

   // 检查数据准备情况
   if(BarsCalculated(fastEmaHandle) < rates_total ||
      BarsCalculated(slowEmaHandle) < rates_total ||
      BarsCalculated(atrHandle) < rates_total)
      return prev_calculated;

   // 获取MA数据 - 关键：不使用ArraySetAsSeries
   double fastEmaData[], slowEmaData[], atrData[];
   // ArraySetAsSeries(fastEmaData, true);  // 注释掉
   
   int copied1 = CopyBuffer(fastEmaHandle, 0, 0, rates_total, fastEmaData);
   int copied2 = CopyBuffer(slowEmaHandle, 0, 0, rates_total, slowEmaData);
   int copied3 = CopyBuffer(atrHandle, 0, 0, rates_total, atrData);
   
   if(copied1 <= 0 || copied2 <= 0 || copied3 <= 0)
   {
      Print("复制数据失败: ", copied1, ", ", copied2, ", ", copied3);
      return prev_calculated;
   }

   // 计算乘数因子
   double Multiply_Factor_1 = 2.0 / (FastEma + 1.0);
   double Multiply_Factor_2 = 2.0 / (SlowEma + 1.0);
   double Multiply_Factor_3 = Multiply_Factor_1 - Multiply_Factor_2;
   if(MathAbs(Multiply_Factor_3) < 1e-10)
   {
      Print("无效的乘数因子");
      return prev_calculated;
   }

   // MT5标准计算方式：正向循环
   int start = prev_calculated == 0 ? 0 : prev_calculated - 1;
   
   Print("=== 断水流计算 ===");
   Print("rates_total=", rates_total, " prev_calculated=", prev_calculated, " start=", start);
   
   // 第一阶段：计算temp1[] - MACD差值
   for(int i = start; i < rates_total; i++)
   {
      temp1[i] = fastEmaData[i] - slowEmaData[i];
   }
   
   // 第二阶段：计算temp2[] - MACD信号线
   for(int i = start; i < rates_total; i++)
   {
      temp2[i] = MAOnArray_Fixed(temp1, SignalMA, SignalMAMode, MathMax(0, i - SignalMA + 1));
   }
   
   // 第三阶段：主趋势线计算
   for(int i = start; i < rates_total; i++)
   {
      // 计算主趋势线值
      double trendValue = (Multiply_Factor_1 * fastEmaData[i] + slowEmaData[i] - 
                          fastEmaData[i] - Multiply_Factor_2 * slowEmaData[i] + temp2[i]) / Multiply_Factor_3;
      
      if(!MathIsValidNumber(trendValue))
         trendValue = i > 0 ? TrendLineBuffer[i-1] : close[i];
         
      TrendLineBuffer[i] = trendValue;
   }
   
   // 第四阶段：信号线和状态判断
   for(int i = start; i < rates_total; i++)
   {
      // 计算信号线
      SignalLineBuffer[i] = MAOnArray_Fixed(TrendLineBuffer, SigMA, SigMAMode, MathMax(0, i - SigMA + 1));
      
      // 状态判断
      state[i] = 0;
      if(TrendLineBuffer[i] > high[i]) state[i] = 1;
      if(TrendLineBuffer[i] < low[i]) state[i] = -1;
      
      // 颜色设置 - 修正：上升橙色，下降绿色
      if(state[i] == 1) 
         TrendColorBuffer[i] = 0;  // 上升趋势：橙色（索引0）
      else if(state[i] == -1) 
         TrendColorBuffer[i] = 1;  // 下降趋势：绿色（索引1）  
      else
         TrendColorBuffer[i] = 0;  // 中性状态：默认橙色
      
      // 箭头设置
      ArrowBuffer[i] = EMPTY_VALUE;
      if(i > 0 && state[i] != state[i-1])
      {
         if(state[i] == 1) {
            ArrowBuffer[i] = TrendLineBuffer[i] + atrData[i] / 2;
            ArrowColorBuffer[i] = 0; // 橙色
         }
         if(state[i] == -1) {
            ArrowBuffer[i] = TrendLineBuffer[i] - atrData[i] / 2;
            ArrowColorBuffer[i] = 1; // 绿色
         }
      }
   }
   
   // 调试输出
   if(prev_calculated == 0)
   {
      Print("=== 计算完成，数据检查 ===");
      for(int j = 0; j < MathMin(5, rates_total); j++)
      {
         Print("[", j, "] trend=", DoubleToString(TrendLineBuffer[j], 5),
               " signal=", DoubleToString(SignalLineBuffer[j], 5),
               " state=", state[j]);
      }
   }
   
   return rates_total;
}
//+------------------------------------------------------------------+